<script setup>
import * as echarts from 'echarts';
import {onMounted, ref} from "vue";
import {getCpuLoadApi} from '@/api/cpuload.js'

//保存所有的图标模型
const chartDomArr  = []
const cpuSpaceArr = ref([48,24])
//存储CPU的所有数据
const cpuAllData = ref([])
const cpuTimeValue = ref('30');

onMounted(async () => {
  //初始化图表，只需要一次
  await initChart();
  //画图
  await getCpuData();
})

//初始化图标eCharts
const initChart=async ()=>{
  let resp = await getCpuLoadApi();
  let data = resp.data;
  for (let i = 0; i < data.length; i++) {
    let chartDom = document.getElementById('cpu-'+(i+1));
    let myChart = echarts.init(chartDom);
    chartDomArr.push(myChart);
  }
}

//获取CPU情况
const getCpuData =async () => {
  let resp = await getCpuLoadApi();
  let data = resp.data;
  for (let i = 0; i < data.length; i++) {
    // 把当前请求返回的这个cpu使用率放回自己的数组中
    if(!cpuAllData.value[i]){
      cpuAllData.value[i] = []
    }
    while(cpuAllData.value[i].length>cpuTimeValue.value){
      cpuAllData.value[i].shift();
    }
    cpuAllData.value[i].push(data[i]);
    drawCpuLoad(i,cpuAllData.value[i]);
  }
  await getCpuData();
}

/**
 * 画CPU图
 * 1.cpu的核名称
 * 2.不要xy轴，展示线条
 * 3.显示为面积图
 * @param cpuIndex
 * @param cpuData
 */
const drawCpuLoad =(cpuIndex, cpuData)=>{
  let myChart = chartDomArr[cpuIndex];
  let option;
  option = {
    title:{
      text: 'CPU-'+(cpuIndex+1),
      textStyle:{
        fontSize: 14,
        color: '#b64422',
      },
    },
    grid:{
      left:'5%',
      right:'5%',
      top:'10%',
      bottom:'10%',
      show: true,
    },
    xAxis: {
      // name: '时间/每秒',
      nameLocation:'middle',
      nameTextStyle:{
        color: 'green',
        fontStyle: 'italic',
      },
      show: false,
      startValue: 1,
      position: 'bottom',
      type: 'category',
    },
    yAxis: {
      name: '使用率',
      nameTextStyle:{
        color: 'green',
        fontStyle: 'italic',
      },
      min: 0,
      max: 1,
      show: false,
      type: 'value'
    },
    series: [
      {
        data: cpuData,
        type: 'line',
        itemStyle: {
          color: 'rgb(136,185,226)'
        },
        smooth: true,
        areaStyle:{},
        symbol:'none',
      }
    ]
  };

  option && myChart.setOption(option);
}

//使用率转百分比
const getLatestCpuData=(cpuIndex)=>{
  if(cpuAllData?.value[cpuIndex] && cpuAllData.value[cpuIndex].length>0){
    let cpuData =  cpuAllData.value[cpuIndex][cpuAllData.value[cpuIndex].length-1]
    // 将数据转换为百分比形式，并保留两位小数
    const percentage = (cpuData * 100).toFixed(2);
    // 返回格式化后的百分比字符串，末尾加上 '%' 符号
    return percentage + '%';
  }else{
    return '0.00%';
  }
}

const changeCpuTime = async () => {
  await getCpuData();

}
</script>

<template>
  <!--  18核的CPU-->
  <div>
    <a-space>CPU展示最大时间（秒）：</a-space>
    <a-select :style="{width:'320px',marginBottom:'10px',marginTop:'5px'}"
              v-model="cpuTimeValue"
              placeholder="请选择"
              @change="changeCpuTime"
    >
      <a-option disabled value="0">请选择</a-option>
      <a-option value="10">10</a-option>
      <a-option value="30">30</a-option>
      <a-option value="60">60</a-option>
      <a-option value="120">120</a-option>
    </a-select>
  </div>
  <a-space wrap align="center" style="padding-left: 20px;">
    <div v-for="i in 18" style="border: 1px solid black;">
      <div :id="`cpu-${i}`" style="height: 200px;width: 480px;" ></div>
      <div style="margin-bottom: 20px;margin-top: 5px;">
        <a-space :size="cpuSpaceArr">
          <div>使用率：{{getLatestCpuData(`${i}`)}}</div>
          <div>最大频率：2.995GHz</div>
        </a-space>
      </div>
    </div>
  </a-space>
</template>

<style scoped>
</style>